package com.sdjz.club.club.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.sdjz.club.club.common.lang.CommonResult;
import com.sdjz.club.club.utils.ImageUtil;
import com.sdjz.club.club.utils.SnowFlow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

@RestController
public class ImageController {

    @RequestMapping(value = "/setImage")
    public void getImage(@RequestParam(name = "file") MultipartFile file) throws IOException {
        long id = SnowFlow.getId();
        ImageUtil.updateImg(file, id);
    }

    @GetMapping(value = "/getImage/{id}")
    public void getImg(@PathVariable(name = "id") String ID, HttpServletResponse response) throws Exception {
        ImageUtil.getImg(response, ID);
    }

    @GetMapping(value = "/getImgFast/{id}")
    public CommonResult getImgFast(@PathVariable(name = "id") String ID) throws Exception {
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();

        try {
            BufferedImage image = ImageIO.read(new FileInputStream("E:\\"+ID));
            if (image != null) {
                ImageIO.write(image, "png", os);
            }
        } catch (IOException e) {
            CommonResult commonResult = CommonResult.fail("获取图片异常,图片不存在");
            os.write(JSONUtil.toJsonStr(commonResult).getBytes(StandardCharsets.UTF_8));
        } finally {
            if (os != null) {
                os.flush();
                os.close();
            }
            BASE64Encoder encoder = new BASE64Encoder();
            String str = "data:image/jpeg;base64,";
            String base64Img = str + encoder.encode(os.toByteArray());
            return CommonResult.succ(
                    MapUtil.builder().put("imgSrc", base64Img).build()
            );
        }
    }
}
